//
//  BuyNowViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Alamofire
import PKHUD
import SwiftyJSON
import Networking

class BuyNowViewController: BaseViewController, BottomShadow, UITableViewDataSource, UITableViewDelegate, DelayExecution,AddressLinstViewControllerDelegate,InvoiceViewControllerDelegate {
    let cellHeight: CGFloat = 88
    @IBOutlet var shadowViews: [UIView]!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var phoneLabel: UILabel!
    
    @IBOutlet weak var defaultAddressLabel: UILabel!
    @IBOutlet weak var mainTableView: UITableView!
    @IBOutlet weak var mainTableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var totalPriceLabel: UILabel!
    
    @IBOutlet weak var invoiceLabel: UILabel!
    
    @IBOutlet weak var invoiceBtn: UIButton!
    @IBOutlet weak var totalPrice: UILabel!
    @IBOutlet weak var transferPrice: UILabel!
    
    var model:payModel?
    var wx:String?
    var tel:String?
    var addressModel :AddressModel?{
        didSet{
            if (addressModel != nil && addressModel?.province != "null" && addressModel?.city != "null") {
                if (pgiIds != nil) {
                    let paramters:[String:String] = ["province":(addressModel?.province!)!, "city" : (addressModel?.city!)!, "pgiIds" : "[\(pgiIds!)]"]
                    self.fetchPriceInfo(paramaters: paramters)
                }
            }
        }
    }
    var carts :[cartModel] = []
    var carIds :[String] = []
    var type: Int = 2
    var number: Int = 0
    var addressId :String = ""
    var commodityModel: GoodsModel!
    var tempModel: SpecificationsModel?
    var invoiceTitle:String = ""
    var taxpayerIdNo:String = ""
    var unitName:String = ""
    var invoiceContent:String = ""
    var orderNumber:String?
    var pgiIds:String?{
        didSet{
            if (addressModel != nil && addressModel?.province != "null" && addressModel?.city != "null") {
                if (pgiIds != nil) {
                    let paramters:[String:String] = ["province":(addressModel?.province!)!, "city" : (addressModel?.city!)!, "pgiIds" : "[\(pgiIds!)]"]
                    self.fetchPriceInfo(paramaters: paramters)
                }
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.titleLabel(text: "填写订单", "knapsack_white")
        setUI()
        self.fetchAddressInfo()
        if self.type == 2 {
            let goodsId :String = (tempModel?.giId!)!
            let specId :String = (tempModel?.id!)!
            let paramates = ["type": self.type, "goodsId": goodsId, "number": self.number, "specificationId": specId] as [String : Any]
            self.fetchProductInfo(paramaters: paramates)
        }else if self.type == 1 {
            let idstr :String = carIds.joined(separator: ",")
            let paramates = ["type": self.type, "pgiIds": "[\(idstr)]"] as [String : Any]
            self.fetchProductInfo(paramaters: paramates)
        }else {
            let paramates = ["orderNumber": self.orderNumber]
            self.fetchProductInfoAgain(paramaters: paramates as! [String : String])
        }
    }
    
    @IBOutlet weak var invoiceBtnAction: UIButton!
    
    
    func setUI() {
        defaultAddressLabel.layoutIfNeeded()
        defaultAddressLabel.layer.cornerRadius = defaultAddressLabel.height / 2
        defaultAddressLabel.layer.borderWidth = 1
        defaultAddressLabel.layer.borderColor = UIColor(hex: 0xB90302).cgColor
        var zP: CGFloat = 1
        for view in shadowViews {
            view.layer.zPosition = zP
            setShadow(view: view, opacity: bottomShadowOpacity, size: CGSize(width: 0, height: 3), color: UIColor.black, cornerradius: CORNERRADIUS)
            zP -= 0.1
        }
        
        totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "合计：￥", firstColor: UIColor.white, firstSize: 16), second: (secondString: "0", secondColor: ONColor.pirceLabelColor, secondSize: 19))
        
        mainTableView.register(UINib(nibName: "\(FillInTheOrderTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        //contentLabel.text = "拉克丝几点啦会计师第六届卡司机端卡拉链科技埃里克圣诞节拉开"
        delayExecution(time: 1) {
//            self.mainTableViewHeight.constant = self.cellHeight * 1
            UIView.animate(withDuration: anTIME, animations: {
                self.view.layoutIfNeeded()
            })


            for view in self.shadowViews {
                view.layer.mask?.removeFromSuperlayer()
                self.setShadow(view: view, opacity: bottomShadowOpacity, size: CGSize(width: 0, height: 3), color: UIColor.black, cornerradius: CORNERRADIUS)

            }
        }
    }
    
    func setAddress(model:AddressModel) {
        self.addressModel = model
        self.nameLabel.text = model.id == "null" ? "暂无收货人" : model.name!
        self.phoneLabel.text = model.id == "null"  ? "暂无收货联系方式" : model.mobile!
        self.addressLabel.text = ""
        if model.id != nil && model.id != "null"  {
            self.addressId = model.id!
            self.addressLabel.text = "\(model.province!)\(model.city!)\(model.county!)\(model.detailedAddress!)"
            let isDefault = Int(model.isDefault!)!
            self.defaultAddressLabel.isHidden = isDefault == 0 ? true : false
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return carts.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? FillInTheOrderTableViewCell
        cell?.bindData(model: carts[indexPath.section])
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    override func setNavigation() {
        
    }
    
    @objc func saveTap() {
        
    }
    
    @IBAction func payTap(_ sender: UIButton) {
        var ids :[String] = []
        for cart in carts {
            ids.append(cart.id!)
        }
        let idstr :String = ids.joined(separator: ",")
        if invoiceBtn.isSelected {
            if invoiceLabel.text == "" {
                self.showToast(msg:"没有填写发票信息")
                return
            }
            let paramaters: [String: Any] = ["pgiIds": "[\(idstr)]", "deliveryAddressId": self.addressId, "invoiceTitle": invoiceTitle, "taxpayerIdNo": taxpayerIdNo, "unitName" : unitName, "invoiceContent":invoiceContent]
            payNow(paramaters: paramaters)
        }else {
            let paramaters: [String: Any] = ["pgiIds": "[\(idstr)]", "deliveryAddressId": self.addressId]
            payNow(paramaters: paramaters)
        }
    }
    
    @IBAction func invoiceBtnAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    func invoiceSave(invoiceTitle: String, taxpayerIdNo: String, unitName: String, invoiceContent: String) {
        self.invoiceTitle = invoiceTitle
        self.taxpayerIdNo = taxpayerIdNo
        self.unitName = unitName
        self.invoiceContent = invoiceContent
        invoiceLabel.text = "\(invoiceTitle) \(taxpayerIdNo)"
    }
    
    // MARK: - 地址点击
    @IBAction func addressTap(_ sender: UITapGestureRecognizer) {
        let addressLinstVC = AddressLinstViewController(nibName: "\(AddressLinstViewController.self)", bundle: nil)
        addressLinstVC.addressDelegate = self
        self.navigationController?.pushViewController(addressLinstVC, animated: true)
    }
    
    func selectedAddress(model: AddressModel) {
        self.setAddress(model: model)
    }
    
    func fetchAddressInfo() -> Void {
        let requesturl = "\(BaseURL)\(addressDefaultUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary!
                                        let model = AddressModel(fromDic: dic)
                                        self.wx = model.serviceWeixin
                                        self.tel = model.serviceTel
                                        self.setAddress(model: model)
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }

        }
    }
    
    func fetchPriceInfo(paramaters:[String: String]) -> Void {
        let requesturl = "\(BaseURL)\(getPriceAndFee)"
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary
                                        let amodel = payModel(fromDic: data!)
                                        
                                        let price :String = (amodel.payAmount)!
                                        let tranPrice :String = (amodel.carriage)!
                                        let allPrice:String = (amodel.actualPayAmount)!
                                        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "合计：￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:allPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.transferPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: tranPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.totalPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:price as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    func fetchProductInfo(paramaters:[String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(payAtOnceUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary
                                        self.model = payModel(fromDic: data!)
                                        let arr = json["data"]["rows"].array!
                                        self.model?.initCarts(arr: arr)
                                        let price :String = (self.model?.payAmount)!
                                        let tranPrice :String = (self.model?.carriage)!
                                        let allPrice:String = (self.model?.actualPayAmount)!
                                        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "合计：￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:allPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.transferPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: tranPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.totalPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:price as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.carts = (self.model?.rows!)!
                                        var ids:String = ""
                                        for (index,item) in self.carts.enumerated()
                                        {
                                            if index > 0 {
                                               ids.append(",")
                                            }
                                            ids.append(item.id!)
                                        }
                                        if ids.count > 0 {
                                            self.pgiIds = ids
                                        }
                                        self.mainTableViewHeight.constant = self.cellHeight * CGFloat(self.carts.count)
                                        self.mainTableView.reloadData()
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                        self.navigationController?.popViewController(animated: true)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    func fetchProductInfoAgain(paramaters:[String: String]) -> Void {
        let requesturl = "\(BaseURL)\(purchaseAgain)"
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary
                                        self.model = payModel(fromDic: data!)
                                        let arr = json["data"]["rows"].array!
                                        self.model?.initCarts(arr: arr)
                                        let price :String = (self.model?.payAmount)!
                                        let tranPrice :String = (self.model?.carriage)!
                                        let allPrice:String = (self.model?.actualPayAmount)!
                                        self.totalPriceLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "合计：￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:allPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.transferPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString: tranPrice as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.totalPrice.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "￥", firstColor: ONColor.subTextColor, firstSize: 13), second: (secondString:price as NSString, secondColor: ONColor.pirceLabelColor, secondSize: 16))
                                        self.carts = (self.model?.rows!)!
                                        var ids:String = ""
                                        for (index,item) in self.carts.enumerated()
                                        {
                                            if index > 0 {
                                                ids.append(",")
                                            }
                                            ids.append(item.id!)
                                        }
                                        if ids.count > 0 {
                                            self.pgiIds = ids
                                        }
                                        self.mainTableViewHeight.constant = self.cellHeight * CGFloat(self.carts.count)
                                        self.mainTableView.reloadData()
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                        self.navigationController?.popViewController(animated: true)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    func payNow(paramaters:[String: Any]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(payNowUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary
                    
                                        let payVC = PayViewController(nibName: "PayViewController", bundle: nil)
                                        payVC.titleLabel(text: "选择支付方式", nil)
                                        payVC.orderId = data?["orderId"]?.string!
                                        self.navigationController?.pushViewController(payVC, animated: true)
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"下单失败")
                                self.navigationController?.popViewController(animated: true)
                            }
                            
        }
    }
    @IBAction func pushKp(_ sender: Any) {
        let invoiceVC = InvoiceViewController(nibName: "\(InvoiceViewController.self)", bundle: nil)
        invoiceVC.invoiceDelegate = self
        invoiceVC.price = self.model?.payAmount
        invoiceVC.wx = self.wx
        invoiceVC.tel = self.tel
        self.navigationController?.pushViewController(invoiceVC, animated: true)
    }
}
